# TODO: Add comment
# 
# Author: guochun
###############################################################################


oneSampling.pToe=function(distanceOBJ,populationData){
	return(randomPointToEvent(distanceOBJ,populationData))  
}


setSampleResult.pToe=function(sampleOBJ,selection,populationData){
	return(appendResult(sampleOBJ,selection,populationData))  
}


randomPointToEvent=function(distanceOBJ,populationData){
	x=sample(seq(distanceOBJ@edge,populationData@plotdim[1]-distanceOBJ@edge,by=0.5),1)
	y=sample(seq(distanceOBJ@edge,populationData@plotdim[2]-distanceOBJ@edge,by=0.5),1)
	window=owin(c(0,populationData@plotdim[1]),c(0,populationData@plotdim[2]))
	e1=ppp(x=x,y=y,window=window,check=F)  
	e2=ppp(x=populationData@x,y=populationData@y,window=window,check=F)
	nd=nncross(e1,e2)
	availible=nd[1,2]
	#the formate of distance result is "fromx" "fromy" "Tox"  "Toy" "Distance"
	attr(availible,"d")=data.frame(xfrom=x,yfrom=y,xTo=e2[nd[1,2]]$x,yTo=e2[nd[1,2]]$y,d=nd[1,1])
	return(availible)
}

samplingQuick.pToe=function(sampleMethod,populationData){
	#browser()
	endPoint=matrix(c(populationData@x,populationData@y),nrow=length(populationData@x))
	#多取8倍的空白点，最后在删除重复点后，若有多余，则可以随机选择需要的点数
	spt=round(sampleMethod@time*8)
	#if(spt>=length(populationData@x))
	#	spt=length(populationData@x)
	
	ovp=TRUE
	i=1
	#if there resample points, then sample again
	while(ovp & i<=sampleMethod@stopLimit){
		if(!sampleMethod@transectLine){
			#x=sample(seq( sampleMethod@edge, populationData@plotdim[1]-sampleMethod@edge,3),spt)
			x=runif(spt,sampleMethod@edge, populationData@plotdim[1]-sampleMethod@edge)
			#y=sample(seq( sampleMethod@edge, populationData@plotdim[2]-sampleMethod@edge,3),spt)
			y=runif(spt,sampleMethod@edge, populationData@plotdim[2]-sampleMethod@edge)
		}else{
			dline=transectLine(sampleMethod,populationData)
			xrange=dline@xrange
			x=runif(spt,xrange[1],xrange[2])
			y=dline@slope*x+dline@b
		}
		
		#focus = ppp(x=x,y=y,window=win,check=FALSE)
		focus=matrix(c(x,y),nrow=length(x))
		#nd=nncross(focus,endPoint)
		
		nd=knnx.index(endPoint,focus,k=sampleMethod@k)[,sampleMethod@k]
		nnid=unique(nd)
		if(length(nnid) < sampleMethod@time){
			ovp=TRUE
		}else{
			temp=table(nd)
			del=match(as.numeric(names(temp)[which(temp>1)]),nd)
			if(length(del)>0){
				nd=nd[-del]
				focus=focus[-del,]
			}
		
			select=sort(sample(1:length(nd),sampleMethod@time))
			nd=nd[select]
			focus=focus[select,]
			ovp=FALSE
		}
		
		i=i+1
	}
	
	if(i<=sampleMethod@stopLimit){
		final.d=endPoint[nd,]
		re=sqrt((final.d[,1]-focus[,1])^2+(final.d[,2]-focus[,2])^2)
		return(re)
	}else{
		return(NA)
	}
		
}

